import React from 'react';
import { Card, Form, Input, Button, Table, Modal, Select, Upload, Image, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

const APP_TYPES = [
  { value: 'android', label: 'Android' },
  { value: 'ios', label: 'iOS' },
  { value: 'windows', label: 'Windows' },
];

const initialData = [
  {
    id: '1',
    appType: 'android',
    appName: '演示App',
    image: 'https://via.placeholder.com/60',
    appVersionBefore: '1.0.0',
    appVersion: '1.1.0',
    notes: '修复若干已知问题，提升稳定性',
    createTime: '2024-08-01 10:00:00',
    downUrl: 'https://example.com/download/app1.apk',
  },
];

export default function AppVersion() {
  const [loading, setLoading] = React.useState(false);
  const [list, setList] = React.useState(initialData);
  const [all, setAll] = React.useState(initialData);
  const [searchForm] = Form.useForm();

  const [modalVisible, setModalVisible] = React.useState(false);
  const [form] = Form.useForm();
  const [editing, setEditing] = React.useState(null);

  const onSearch = (values) => {
    const keyword = (values.appName || '').toLowerCase();
    setList(all.filter((it) => it.appName.toLowerCase().includes(keyword)));
  };

  const onReset = () => {
    searchForm.resetFields();
    setList(all);
  };

  const openAdd = () => {
    setEditing(null);
    form.resetFields();
    setModalVisible(true);
  };

  const openEdit = (row) => {
    setEditing(row);
    form.setFieldsValue({
      appType: row.appType,
      appVersion: row.appVersion,
      appVersionBefore: row.appVersionBefore,
      appImage: row.image,
      appName: row.appName,
      downUrl: row.downUrl,
      notes: row.notes,
    });
    setModalVisible(true);
  };

  const onModalOk = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        id: editing?.id || String(Date.now()),
        appType: values.appType,
        appVersion: values.appVersion,
        appVersionBefore: values.appVersionBefore,
        image: values.appImage || 'https://via.placeholder.com/60',
        appName: values.appName,
        downUrl: values.downUrl,
        notes: values.notes || '',
        createTime: editing?.createTime || new Date().toLocaleString(),
      };
      let nextAll;
      if (editing) {
        nextAll = all.map((it) => (it.id === editing.id ? payload : it));
        message.success('更新成功');
      } else {
        nextAll = [payload, ...all];
        message.success('新增成功');
      }
      setAll(nextAll);
      // 保持当前搜索条件
      const keyword = (searchForm.getFieldValue('appName') || '').toLowerCase();
      setList(nextAll.filter((it) => it.appName.toLowerCase().includes(keyword)));
      setModalVisible(false);
      setEditing(null);
    } catch (e) {}
  };

  const columns = [
    {
      title: '平台类型',
      dataIndex: 'appType',
      width: 120,
      align: 'center',
      render: (val) => APP_TYPES.find((t) => t.value === val)?.label || val,
    },
    { title: '应用名称', dataIndex: 'appName', width: 160, align: 'center' },
    {
      title: '图标',
      width: 120,
      align: 'center',
      render: (_, row) => <Image width={60} height={60} src={row.image} />,
    },
    { title: '旧版本', dataIndex: 'appVersionBefore', width: 160, align: 'center' },
    { title: '新版本', dataIndex: 'appVersion', width: 120, align: 'center' },
    { title: '备注', dataIndex: 'notes' },
    { title: '创建时间', dataIndex: 'createTime', width: 180, align: 'center' },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      align: 'center',
      render: (_, row) => (
        <Button size="small" onClick={() => openEdit(row)}>
          编辑
        </Button>
      ),
    },
  ];

  return (
    <div className="app-version">
      {/* 搜索区域 */}
      <Card className="vue-padding radius" bordered={false} style={{ marginBottom: 12 }}>
        <Form form={searchForm} layout="inline" onFinish={onSearch}>
          <Form.Item label="应用名称" name="appName">
            <Input placeholder="请输入应用名称" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginRight: 8 }}>
              查询
            </Button>
            <Button onClick={onReset} style={{ marginRight: 8 }}>
              重置
            </Button>
            <Button type="dashed" icon={<PlusOutlined />} onClick={openAdd}>
              新增版本
            </Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 列表区域 */}
      <Card className="vue-padding radius" bordered={false}>
        <Table
          loading={loading}
          dataSource={list}
          columns={columns}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ y: 638 }}
        />
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={editing ? '编辑版本' : '新增版本'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={onModalOk}
        destroyOnClose
        maskClosable={false}
      >
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
          <Form.Item label="平台类型" name="appType" rules={[{ required: true, message: '请选择平台类型' }]}> 
            <Select options={APP_TYPES} placeholder="请选择" />
          </Form.Item>
          <Form.Item label="应用名称" name="appName" rules={[{ required: true, message: '请输入应用名称' }]}> 
            <Input placeholder="应用名称" />
          </Form.Item>
          <Form.Item label="旧版本" name="appVersionBefore" rules={[{ required: true, message: '请输入旧版本号' }]}> 
            <Input placeholder="如：1.0.0" />
          </Form.Item>
          <Form.Item label="新版本" name="appVersion" rules={[{ required: true, message: '请输入新版本号' }]}> 
            <Input placeholder="如：1.1.0" />
          </Form.Item>
          <Form.Item label="下载地址" name="downUrl" rules={[{ required: true, message: '请输入下载地址' }]}>
            <Input placeholder="https://..." />
          </Form.Item>
          <Form.Item label="图标地址" name="appImage">
            <Input placeholder="https://image.url/60x60" />
          </Form.Item>
          <Form.Item label="备注" name="notes">
            <Input.TextArea placeholder="版本说明" rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}